﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Data;

namespace MyClever.Lib
{
    public class AppDomainLoader
    {
        public static AppDomain CreateAppDomain(string applicationName, string privateBinPath)
        {
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationName = applicationName + Guid.NewGuid().ToString();
            setup.ApplicationBase = setup.ApplicationBase = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyCleverFriend");
            setup.PrivateBinPath = privateBinPath;

            AppDomain appDomain = AppDomain.CreateDomain(applicationName, null, setup);
            Debug.Assert(appDomain != null);

            return appDomain;
        }

        public static AppDomain CreateAppDomain(PluginPath pluginPath, string applicationName)
        {
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationName = applicationName + Guid.NewGuid().ToString();
            setup.ApplicationBase = setup.ApplicationBase = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyCleverFriend");
            setup.PrivateBinPath = String.Format("{0};{1}", pluginPath.RelativeDataPath, pluginPath.RelativeLibraryPath);
            setup.CachePath = Path.Combine(pluginPath.BasePath, "cache" + Path.DirectorySeparatorChar);
            setup.ShadowCopyFiles = "true";
            setup.ShadowCopyDirectories = pluginPath.FullPath;

            AppDomain appDomain = AppDomain.CreateDomain(applicationName, null, setup);
            Debug.Assert(appDomain != null);

            return appDomain;
        }

        public static object CreateInstanceInAppDomain(AppDomain appDomain, string assemblyName, string typeName)
        {
            object remoteObject = appDomain.CreateInstanceAndUnwrap(assemblyName, typeName);
            Debug.Assert(remoteObject != null);

            return remoteObject;
        }

        public static void UnloadAppDomain(AppDomain appDomain)
        {
            AppDomain.Unload(appDomain);
            appDomain = null;
        }
    }
}
